package com.uni.crawl.common.util.crawl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uni.crawl.common.enums.crawl.CrawlTemplateBuildInParamEnum;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class XsltTemplatePiplineProcessor {

    public static Object process(XsltTemplatePipline pipline, String input) {
        if (pipline == null) {
            return null;
        }
        for (String tmplStr : pipline.getTemplateList()) {
            try {
                Transformer transformer = ExtractUtils.getTransformerByString(tmplStr);
                Source source = ExtractUtils.getSourceByString(input);

                JSONObject jsonObject = ExtractUtils.getJSONObject(transformer, source);
                if (jsonObject.containsKey(CrawlTemplateBuildInParamEnum.PIPLINE_RESULT.getParam())) {
                    // 如果当前管道有约定的result结果，就把结果继续向下传递
                    input = jsonObject.getStr(CrawlTemplateBuildInParamEnum.PIPLINE_RESULT.getParam());
                } else {
                    return jsonObject;
                }
            } catch (TransformerException e) {
                throw new RuntimeException(e);
            }
        }
        return JSONUtil.createObj().append("msg", "未按预期处理管道");
    }

}
